package com.xbongbong.crm.perform.query.list.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.service.CustomerCommunicateListService;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasListGroupEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.BusinessListHelp;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.parent.help.ListGroupHelp;
import com.xbongbong.paas.model.PaasCommentModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasListGroupModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.ButtonExtraPojo;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.explain.HandleExplainHelp;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.parent.pojo.list.ButtonPermissionPojo;
import com.xbongbong.parent.pojo.list.CustomerCommunicateAnalysisVO;
import com.xbongbong.parent.pojo.list.FieldListPojo;
import com.xbongbong.pro.constant.RangeScreenConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.enums.permission.enums.ViewProPermissionAliasEnum;
import com.xbongbong.pro.formexplain.pojo.HandleExplainPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.pro.weblist.pojo.CustomerCommunicatePojo;
import com.xbongbong.pro.weblist.pojo.vo.CommunicateVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.BusinessCommentEnum;
import com.xbongbong.saas.enums.ListTopButtonEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.SaasSubButtonEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.model.LikeModel;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @author sunshaoxiang
 * @ClassName CustomerCommunicateListServiceImpl
 * @Description 跟进记录列表页业务层实现
 * @Date 2022/5/31 15:15
 * @Version 1.0
 **/
@Service("customerCommunicateListServiceImpl")
public class CustomerCommunicateListServiceImpl implements CustomerCommunicateListService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerCommunicateListServiceImpl.class);


    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private HandleExplainHelp handleExplainHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private UserModel userModel;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private PaasListGroupModel paasListGroupModel;
    @Resource
    private ListGroupHelp listGroupHelp;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private FormDataListAnalysisDataHelp formDataListAnalysisDataHelp;
    @Resource
    private PaasCommentModel paasCommentModel;
    @Resource
    private LikeModel likeModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private BusinessListHelp businessListHelp;





    @Override
    public CommunicateVO list(FormDataListDTO formDataListDTO) throws XbbException {
        CommunicateVO communicateVO = new CommunicateVO();
        //获取表单
        PaasFormEntityExt paasFormEntity = getForm(formDataListDTO.getFormId(), formDataListDTO.getCorpid());
        formDataListDTO.setMenuId(paasFormEntity.getMenuId());
        //获取并处理表单解释
        FieldListPojo fieldListPojo = new FieldListPojo(formDataListDTO.getCorpid(), formDataListDTO.getFormId(), formDataListDTO.getAppId(), formDataListDTO.getDefaultGroup(),
                formDataListDTO.getListGroupId(), formDataListDTO.getSaasMark(), formDataListDTO.getBusinessType(), formDataListDTO.getSubBusinessType(), formDataListDTO.getLoginUser(), paasFormEntity);
        HandleExplainPojo explainPojo = getExplain(fieldListPojo);
        //获取并处理表单数据
        CustomerCommunicateAnalysisVO  customerCommunicateAnalysisVO = getData(formDataListDTO, explainPojo);
        //设置权限按钮 这里只有头部权限按钮
        ButtonPermissionPojo buttonPermissionPojo = handlePermissionButton(formDataListDTO.getLoginUser(), formDataListDTO.getBusinessType(), formDataListDTO.getSubBusinessType(), formDataListDTO.getMenuId(), formDataListDTO.getCorpid());
        //封装VO对象返回给前端
        communicateVO.setResultMap(customerCommunicateAnalysisVO.getCustomerCommunicatePojos());
        communicateVO.setPageHelper(customerCommunicateAnalysisVO.getPageHelper());
        communicateVO.setAddPermission(buttonPermissionPojo.getAddPermission());
        communicateVO.setTopPermissions(buttonPermissionPojo.getTopPermissions());
        return communicateVO;
    }

    /**
     * 设置权限按钮
     * @param userVO
     * @param businessType
     * @param subBusinessType
     * @param menuId
     * @param corpid
     * @return
     * @throws XbbException
     */
    private ButtonPermissionPojo handlePermissionButton(UserVO userVO, Integer businessType, Integer subBusinessType, Long menuId, String corpid)throws XbbException {
        ButtonPermissionPojo buttonPermissionPojo = new ButtonPermissionPojo();
        List<ListTopButtonEnum> topButtonEnumList = ListTopButtonEnum.getByBusinessType(businessType);
        List<ButtonPojo> topButtonList = new ArrayList<>();
        PaasMenuEntity paasMenuEntity = paasMenuModel.getByKey(menuId, corpid);
        if (Objects.isNull(paasMenuEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
        }
        for (ListTopButtonEnum topButtonEnum : topButtonEnumList) {
            if ((Objects.equals(topButtonEnum, ListTopButtonEnum.COMMUNICATE_ADD) && !userVO.getPermSet().contains(ProPermissionAliasEnum.CUSTOMER_COMMUNICATE_ADD.getAlias()))
                    || (Objects.equals(topButtonEnum, ListTopButtonEnum.COMMUNICATE_EXPORT) && !userVO.getPermSet().contains(ProPermissionAliasEnum.CUSTOMER_COMMUNICATE_EXPORT.getAlias()))
                    || (Objects.equals(topButtonEnum, ListTopButtonEnum.COMMUNICATE_IMPORT) && !userVO.getPermSet().contains(ProPermissionAliasEnum.CUSTOMER_COMMUNICATE_IMPORT.getAlias()))) {
                continue;
            }
            ButtonPojo buttonPojo = new ButtonPojo();
            BeanUtil.copyProperties(topButtonEnum.getAnEnum(), buttonPojo);
            topButtonList.add(buttonPojo);
            // 移动端列表页新建按钮
            if (Objects.equals(buttonPojo.getAttr(), SaasButtonEnum.ADD.getAttr())) {
                buttonPermissionPojo.setAddPermission(true);
            }
            if (Objects.equals(topButtonEnum.getAnEnum().getAttr(), SaasButtonEnum.IMPORT.getAttr())) {
                ButtonExtraPojo buttonExtraPojo = new ButtonExtraPojo();
                buttonExtraPojo.setImportTitle(paasMenuEntity.getName());
                buttonPojo.setButtonExtra(buttonExtraPojo);
            }
            if (Objects.equals(topButtonEnum.getAnEnum().getAttr(), SaasButtonEnum.EXPORT.getAttr())) {
                List<ButtonPojo> subButtonList = new ArrayList<ButtonPojo>(){{
                    add(new ButtonPojo(){{BeanUtil.copyProperties(topButtonEnum.getAnEnum(), this);}});
                }};
                List<SaasSubButtonEnum> saasSubButtonEnumList = SaasSubButtonEnum.getByPermissionAlias(subBusinessType,topButtonEnum,userVO.getPermSet());
                saasSubButtonEnumList.forEach(item->{
                    subButtonList.add(new ButtonPojo(){{setAttr(item.getAlias());setValue(item.getName());}});
                });
                buttonPojo.setSubButtons(subButtonList);
            }
        }
        buttonPermissionPojo.setTopPermissions(topButtonList);
        return buttonPermissionPojo;
    }

    @Override
    public PaasFormEntityExt getForm(Long formId, String corpid) throws XbbException {
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        if (paasFormEntityExt == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        return paasFormEntityExt;
    }

    @Override
    public HandleExplainPojo getExplain(FieldListPojo fieldListPojo) throws XbbException {
        //获取表单解释
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(fieldListPojo.getFormId(), fieldListPojo.getCorpid());
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);

        //表单解释通用解析
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO(explainList, fieldListPojo.getForm(), fieldListPojo.getCorpid(), fieldListPojo.getUserVO().getUserId(), fieldListPojo.getUserVO(), true, fieldListPojo.getSubBusinessType());
        HandlerExplainVO handlerExplainVO = handleExplainHelp.handleExplain(handlerExplainDTO);
        if (handlerExplainVO == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }

        HandleExplainPojo handleExplainPojo = new HandleExplainPojo();
        explainList = handlerExplainVO.getHeadList();
        handleExplainPojo.setExplainList(explainList);
        handleExplainPojo.setExplainMap(ExplainUtil.getExplainMap(JSONArray.toJSONString(explainList)));
        return handleExplainPojo;
    }

    @Override
    public CustomerCommunicateAnalysisVO getData(FormDataListDTO formDataListDTO, HandleExplainPojo explainPojo) throws XbbException {
        //获取数据前置处理
        beforeGetDataHandle(formDataListDTO);
        formDataListDTO.setExplainMap(explainPojo.getExplainMap());
        //Es查询数据

        PaasFormDataEsListVO formDataListVO = paasFormDataEsModel.list(formDataListDTO, IndexTypeEnum.IDX_SAAS_CUSTOMER_COMMUNICATE);
        //数据解析
        return analysisData(formDataListDTO, explainPojo, formDataListVO);


    }

    /**
     * 数据解析
     * @param formDataListDTO
     * @param explainPojo
     * @param formDataListVO
     * @return
     * @throws XbbException
     */
    private CustomerCommunicateAnalysisVO analysisData(FormDataListDTO formDataListDTO, HandleExplainPojo explainPojo, PaasFormDataEsListVO formDataListVO) throws XbbException {
        CustomerCommunicateAnalysisVO customerCommunicateAnalysisVO = new CustomerCommunicateAnalysisVO();
        // web端逻辑，主要处理下关于关联数据，用户，部门数据回显的问题
        formDataListVO.setHeadList(explainPojo.getExplainList());
        formDataListVO.setExplainMap(explainPojo.getExplainMap());
        formDataListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO);
        //通用数据解析 这里感觉不是很好拆分
        List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
        List<Long> dataIdIn = new ArrayList<>();
        List<CustomerCommunicatePojo> customerCommunicatePojoList = new ArrayList<>();

        // 校验联系人字段是否可见
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        handlerExplainDTO.setPaasFormEntityExt(explainPojo.getForm());
        handlerExplainDTO.setExplainList(explainPojo.getExplainList());
        boolean contactAttrVisible = commonHelp.attrCanSee(CustomerCommunicateEnum.CONTACT_ARRAY.getAttr(), explainPojo.getExplainMap(), handlerExplainDTO);
        if (CollectionsUtil.isNotEmpty(paasFormDataESList)) {
            for (PaasFormDataEntityExt entity : paasFormDataESList) {
                dataIdIn.add(entity.getDataId());
            }
            dataIdIn.add(-1L);
            Map<Long,Integer> commnetCountMap = paasCommentModel.getCommnetCountMap(dataIdIn,formDataListDTO.getCorpid(), BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode());
            Map<Long,Integer> likeCountMap = likeModel.getLikeCountMap(dataIdIn,formDataListDTO.getCorpid(),BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode());
            List<Long> hasCommentIdList = paasCommentModel.hasMyComment(dataIdIn,formDataListDTO.getCorpid(),BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode(),formDataListDTO.getUserId());
            List<Long> hasLikeIdList = likeModel.hasMyLike(dataIdIn,formDataListDTO.getCorpid(),BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode(),formDataListDTO.getUserId());
            for (PaasFormDataEntityExt entity : paasFormDataESList) {
                JSONObject data = entity.getData();
                Long customerId = data.getLong(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr());
                String customerName = data.getString(CustomerCommunicateEnum.CUSTOMER_NAME_LINK_TEXT.getAttr());
                String creatorId = data.getString(CustomerCommunicateEnum.USER_ID.getAttr());
                String userName = data.getString(CustomerCommunicateEnum.USER_NAME.getAttr());
                Object userAvatar = data.get(CustomerCommunicateEnum.USER_AVATAR.getAttr());
                try {
                    CustomerCommunicatePojo customerCommunicatePojo = commonHelp.setCommunicatePojo(commnetCountMap, likeCountMap, hasCommentIdList, hasLikeIdList, entity, data, customerId, customerName, creatorId, userName, userAvatar, explainPojo.getExplainMap(), contactAttrVisible, DistributorMarkEnum.OTHER.getCode());
                    customerCommunicatePojoList.add(customerCommunicatePojo);
                } catch (Exception e) {
                    LOGGER.error("客户跟进保存错误", e);
                }
            }
        }
        customerCommunicateAnalysisVO.setCustomerCommunicatePojos(customerCommunicatePojoList);
        customerCommunicateAnalysisVO.setPageHelper(formDataListVO.getPageHelper());
        return customerCommunicateAnalysisVO;
    }


    /**
     * 之前的方法是将所有的前置处理动作都塞到formDataListDTO里面...
     * @param formDataListDTO
     */
    private void beforeGetDataHandle(FormDataListDTO formDataListDTO)throws XbbException {
        // 对移动端的客户名称电话查询作处理
        dealCutomerIdByDingtalk(formDataListDTO);
        //权限条件处理
        if (!formDataListDTO.getLoginUser().getPermSet().contains(ViewProPermissionAliasEnum.CUSTOMER_COMMUNICATE_VIEW.getAlias())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050, String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), ViewProPermissionAliasEnum.CUSTOMER_COMMUNICATE_VIEW.getMemo()));
        }
        ConditionsEntityExt dataPermissionCondition = getDataPermissionCondition(formDataListDTO.getBusinessType(), formDataListDTO.getLoginUser(), formDataListDTO.getSubBusinessType());

        // 共享权限处理
//        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(Collections.singletonList(dataPermissionCondition), Collections.singletonList(formDataListDTO.getFormId()), formDataListDTO.getLoginUser());
//        formDataListDTO.setSharePermission(sharePermission);
        if (dataPermissionCondition != null) {
            formDataListDTO.getConditions().add(dataPermissionCondition);
        }
        //app端特有范围条件
        if (isDingtalk(formDataListDTO.getPlatform())) {
            saasListDataPermissionHelp.dingtalkRangeScreen(formDataListDTO.getConditions(), formDataListDTO.getLoginUser(), XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode(), formDataListDTO.getSubBusinessType(), formDataListDTO.getPlatform());
        } else {
            //web端范围条件
            rangeScreen(formDataListDTO.getConditions(), formDataListDTO.getCorpid(), formDataListDTO.getCommonFilter());
        }
        //没有注释的条件处理
        setCondition(formDataListDTO);
        //默认排序 字段显示
        Map<String, String> sortMap = businessListHelp.getSortMap(formDataListDTO.getSubBusinessType(), formDataListDTO.getBusinessType(), formDataListDTO.getFormId(), formDataListDTO.getAppId(), formDataListDTO.getCorpid(), formDataListDTO.getListGroupId(), formDataListDTO.getUserId(), formDataListDTO.getSortMap());
        formDataListDTO.setSortMap(sortMap);
        sortMap = formDataListDTO.getSortMap();
        if (Objects.isNull(sortMap) || sortMap.isEmpty()) {
            Map<String, String> defaultSort = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            defaultSort.put("field", CustomerCommunicateEnum.COMMUNICATE_TIME.getAttr());
            defaultSort.put("sort", SortOrder.DESC.name());
            formDataListDTO.setSortMap(defaultSort);
        }
        formDataListDTO.setSearchSubForm(false);




    }

    /**
     * 重构前 -> com.xbongbong.saas.service.impl.CustomerCommunicateServiceImpl#setCondition(com.xbongbong.paas.pojo.dto.FormDataListDTO)
     * @param formDataListDTO
     */
    private void setCondition(FormDataListDTO formDataListDTO)throws XbbException {
        if(formDataListDTO.getListGroupId() != null){
            PaasListGroupEntity paasListGroupEntity ;
            if (formDataListDTO.getListGroupId() != null && Objects.equals(formDataListDTO.getDefaultGroup(), 0)) {
                paasListGroupEntity = paasListGroupModel.getByKey(formDataListDTO.getListGroupId(), formDataListDTO.getCorpid());
            } else {
                paasListGroupEntity = listGroupHelp.getDefaultGroup(formDataListDTO);
            }
            if (paasListGroupEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.LIST_GROUP_NOT_EXIST);
            }
            List<ConditionsEntityExt> listGroupConditionList = JSONArray.parseArray(paasListGroupEntity.getJsonData(), ConditionsEntityExt.class);
            if(listGroupConditionList != null && !listGroupConditionList.isEmpty()){
                List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
                conditionList.addAll(listGroupConditionList);
                formDataListDTO.setConditions(conditionList);
            }
        }

        if (formDataListDTO.getCommonFilter() != null){
            List<ConditionsEntityExt> conditionsEntityExtList = formDataListDTO.getConditions();
            conditionsEntityExtList = conditionsEntityExtList == null ? new ArrayList<>() : conditionsEntityExtList;
            for (Map.Entry<String,Object> entry : formDataListDTO.getCommonFilter().entrySet()){
                if (Objects.isNull(entry.getValue()) || (Objects.nonNull(entry.getValue()) && StringUtil.isEmpty(entry.getValue().toString()))){
                    continue;
                }
                ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                conditionsEntityExt.setAttr(entry.getKey());
                if (Objects.isNull(CustomerCommunicateEnum.getByAttr(entry.getKey()))) {
                    continue;
                }
                Integer fieldType = CustomerCommunicateEnum.getByAttr(entry.getKey()).getFieldType();
                conditionsEntityExt.setFieldType(fieldType);
                if (Objects.equals(fieldType,FieldTypeEnum.DATETIME.getType())){
                    conditionsEntityExt.setSymbol(ConditionEnum.RANGE.getSymbol());
                    List<String> stringList = JSONArray.parseArray(JSONArray.toJSONString(entry.getValue()),String.class);
                    List<Object> valueList = new ArrayList<>();
                    valueList.add(DateTimeUtil.getInt(stringList.get(0),DateTimeUtil.SDFDate));
                    valueList.add(DateTimeUtil.getInt(stringList.get(1),DateTimeUtil.SDFDate) + TimeConstant.SECONDS_PER_DAY);
                    conditionsEntityExt.setValue(valueList);
                }else if (Objects.equals(fieldType,FieldTypeEnum.COMBO.getType())){
                    conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(entry.getValue()));
                }else {
                    conditionsEntityExt.setSymbol(ConditionEnum.LIKE.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(entry.getValue()));
                }
                conditionsEntityExtList.add(conditionsEntityExt);
            }
            formDataListDTO.setConditions(conditionsEntityExtList);
        }
        // 添加条件排除“项目日志”
        formDataListDTO.getConditions().add(new ConditionsEntityExt(FieldTypeEnum.LOG_TYPE.getAlias(),"",FieldTypeEnum.LOG_TYPE.getType(),ConditionEnum.EQUAL.getSymbol(),Collections.singletonList(0)));
    }

    /**
     * 重构前 -> com.xbongbong.saas.service.impl.CustomerCommunicateServiceImpl#rangeScreen(com.xbongbong.paas.pojo.dto.FormDataListDTO)
     * @param conditionsEntityExtList
     * @param corpid
     * @param commonFilter
     * @throws XbbException
     */
    private void rangeScreen(List<ConditionsEntityExt> conditionsEntityExtList, String corpid, JSONObject commonFilter) throws XbbException{
        if (Objects.isNull(commonFilter)) {
            return;
        }
        JSONObject rangeScreen = commonFilter.getJSONObject(RangeScreenConstant.RANGE_SCREEN);
        if (Objects.isNull(rangeScreen) || Objects.isNull(rangeScreen.get(RangeScreenConstant.TYPE)) || StringUtil.isEmpty(rangeScreen.getString(RangeScreenConstant.TYPE)) || Objects.isNull(rangeScreen.get(RangeScreenConstant.VALUE))) {
            return;
        }

        String type;
        List<String> values;
        try {
            type = rangeScreen.getString(RangeScreenConstant.TYPE);
            values = rangeScreen.getJSONArray(RangeScreenConstant.VALUE).toJavaList(String.class);
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001.getCode(), "customerCommunicateServiceimpl.rangeScreen中的commonFilter参数错误");
        }
        if (CollectionsUtil.isEmpty(values)) {
            return;
        }
        if (Objects.equals(type, RangeScreenConstant.DEPARTMENT)) {
            List<Long> deptIds = new ArrayList<>(values.size());
            values.forEach(item -> deptIds.add(Long.valueOf(item)));
            values = userModel.getUserIdsRecursionDep(deptIds, corpid, 1, true);
        }

        conditionsEntityExtList = conditionsEntityExtList == null ? new ArrayList<>() : conditionsEntityExtList;
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(CustomerCommunicateEnum.CREATOR_ID.getAttr(), "",
                CustomerCommunicateEnum.CREATOR_ID.getFieldType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(values));
        conditionsEntityExtList.add(conditionsEntityExt);
    }

    /**
     * 权限条件封装
     * 重构前 -> com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp#listDataPermission(boolean, java.util.List, com.xbongbong.paas.toolbox.wrap.UserVO, java.lang.Integer, java.lang.Integer)
     * @param businessType
     * @param userVO
     * @param subBusinessType
     * @return
     */
    private ConditionsEntityExt getDataPermissionCondition(Integer businessType, UserVO userVO, Integer subBusinessType) {
        if (userVO.isMaxDataPermission()){
            return null;
        }
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(userVO, userEntity);
        Integer dataPermission = userModel.getDataPermission(userEntity);
        List<String> userIdIn = userModel.getSubIdListByDataPermission(dataPermission, userVO.getUserId(), userVO.getCorpid(), BasicConstant.ZERO,false);
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
        conditionsEntityExt.setValue(new ArrayList<>(userIdIn));
        conditionsEntityExt.setAttr(CustomerCommunicateEnum.CREATOR_ID.getAttr());
        conditionsEntityExt.setFieldType(CustomerCommunicateEnum.CREATOR_ID.getFieldType());
        return conditionsEntityExt;
    }

    /**
     * 对移动端的客户名称电话查询作处理 代码里没有判断是否是移动端
     * 重构前 -> com.xbongbong.saas.service.impl.CustomerCommunicateServiceImpl#dealCutomerIdByDingtalk(com.xbongbong.paas.pojo.dto.FormDataListDTO)
     * @param formDataListDTO
     */
    private void dealCutomerIdByDingtalk(FormDataListDTO formDataListDTO) throws XbbException{
        List<ConditionsEntityExt> conditionsList = formDataListDTO.getConditions();
        for (ConditionsEntityExt conditionsEntityExt : conditionsList) {
            if (Objects.equals(conditionsEntityExt.getAttr(), "nameLike")) {
                String nameLike = conditionsEntityExt.getValue().get(0).toString();
                List<Object> customerIdIn = new ArrayList<>();
                if (nameLike != null && !StringUtil.isEmpty(nameLike, true)) {
                    BoolQueryBuilder nameLikeQuery = boolQuery();
                    nameLikeQuery.filter(termQuery("corpid.keyword", formDataListDTO.getCorpid()));
                    nameLikeQuery.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                    EsUtil.setNameLike(SaasMarkEnum.SAAS.getCode(), nameLike, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), false, nameLikeQuery,true,null, formDataListDTO.getLoginUser());
                    List<PaasFormDataEntityExt> customerList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CUSTOMER,nameLikeQuery,PaasFormDataEntityExt.class, Collections.singletonList(FieldTypeEnum.DATAID.getAlias()));
                    customerList.forEach(item ->{
                        customerIdIn.add(item.getDataId());
                    });
                    if (customerIdIn.isEmpty()) {
                        customerIdIn.add(-1);
                    }
                    conditionsEntityExt.setAttr(CustomerCommunicateEnum.CUSTOMER_NAME.getAttr());
                    conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                    conditionsEntityExt.setValue(new ArrayList<>(customerIdIn));
                }
            }
        }
    }

    /**
     * 钩子函数，移动端有部门特有操作
     */
    private boolean isDingtalk(String platForm){
        return Objects.equals(platForm, "dingtalk");
    }
}
